package com.openx.cloud.server.autoconfigure.security;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * 自定义有限期权限类
 *
 * @author liuyadu
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public final class DateGrantedAuthority implements GrantedAuthority {

    private static final long serialVersionUID = -4682269495406460314L;

    /**
     * 权限标识
     */
    private String authority;

    /**
     * 开始时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startTime;

    /**
     * 结束时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endTime;

    /**
     * 是否为有效时间
     *
     * @return
     */
    @JsonProperty("isInTime")
    public Boolean getIsInTime() {
        if (startTime != null && endTime != null) {
            return DateUtil.isIn(new Date(), startTime, endTime);
        }
        return true;
    }

    public DateGrantedAuthority() {
    }

    public DateGrantedAuthority(String authority) {
        Assert.hasText(authority, "A granted authority textual representation is required");
        this.authority = authority;
    }

    public DateGrantedAuthority(String authority, Date startTime, Date endTime) {
        Assert.hasText(authority, "A granted authority textual representation is required");
        this.authority = authority;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    @Override
    public String getAuthority() {
        return this.authority;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else {
            return obj instanceof DateGrantedAuthority ? this.authority.equals(((DateGrantedAuthority) obj).authority) : false;
        }
    }

    @Override
    public int hashCode() {
        return this.authority.hashCode();
    }

    @Override
    public String toString() {
        return this.authority;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
}
